import DiyApi from '@/sheep/api/promotion/diy';
import { defineStore } from 'pinia';
import $platform from '@/sheep/platform';
import $router from '@/sheep/router';
import user from './user';
import sys from './sys';

interface AppInfo {
  name: string; // 商城名称
  logo: string; // logo
  version: string; // 版本号
  copyright: string; // 版权信息 I
  copytime: string; // 版权信息 II
  cdnurl: string; // 云存储域名
  filesystem: string; // 云存储平台
}

interface PlatformInfo {
  share: {
    methods: string[]; // 支持的分享方式
    forwardInfo: Record<string, unknown>; // 默认转发信息
    posterInfo: Record<string, unknown>; // 海报信息
    linkAddress: string; // 复制链接地址
  };
  bind_mobile: number; // 登陆后绑定手机号提醒 (弱提醒，可手动关闭)
}

interface BasicTemplate {
  tabBar?: Record<string, unknown>;
  theme?: string;
}

interface HomeTemplate {
  style: Record<string, unknown>;
  data: any[];
}

interface UserTemplate {
  style: Record<string, unknown>;
  data: any[];
}

interface AppStoreState {
  info: AppInfo;
  platform: PlatformInfo;
  chat: Record<string, string>;
  template: {
    basic: BasicTemplate;
    home: HomeTemplate;
    user: UserTemplate;
  };
  shareInfo: Record<string, unknown>;
  has_wechat_trade_managed: number; // 小程序发货信息管理  0 没有 || 1 有
}

const app = defineStore({
  id: 'app',
  state: (): AppStoreState => ({
    info: {
      name: '',
      logo: '',
      version: '',
      copyright: '',
      copytime: '',
      cdnurl: '',
      filesystem: '',
    },
    platform: {
      share: {
        methods: [],
        forwardInfo: {},
        posterInfo: {},
        linkAddress: '',
      },
      bind_mobile: 0,
    },
    chat: {},
    template: {
      basic: {},
      home: {
        style: {},
        data: [],
      },
      user: {
        style: {},
        data: [],
      },
    },
    shareInfo: {},
    has_wechat_trade_managed: 0,
  }),
  actions: {
    async init(templateId: string | null = null): Promise<boolean> {
      // 检查网络
      const networkStatus = await $platform.checkNetwork();
      if (!networkStatus) {
        $router.error('NetworkError');
      }

      // 加载装修配置
      await adaptTemplate(this.template, templateId);

      // TODO: 未来支持管理后台可配；对应 https://api.openshop.example.com/shop/api/init
      if (true) {
        this.info = {
          name: 'OpenShop',
          logo: '/static/images/openshop-logo.png',
          version: '1.0.0',
          copyright: '全部开源，个人与企业可 100% 免费使用',
          copytime: 'Copyright© 2014-2024',
          cdnurl: 'https://file.example.com', // 云存储域名
          filesystem: 'qcloud', // 云存储平台
        };
        this.platform = {
          share: {
            methods: ["poster", "link"],
            linkAddress: "https://openshop.example.com/#/",
            posterInfo: {
              "user_bg": "/static/img/shop/config/user-poster-bg.png",
              "goods_bg": "/static/img/shop/config/goods-poster-bg.png",
              "groupon_bg": "/static/img/shop/config/groupon-poster-bg.png"
            }
          },
          bind_mobile: 0
        };
        this.chat = {
          chat_domain: "https://api.openshop.example.com/chat",
          room_id: "admin"
        }
        this.has_wechat_trade_managed = 0;

        // 加载主题
        const sysStore = sys();
        sysStore.setTheme();

        // 模拟用户登录
        const userStore = user();
        if (userStore.isLogin) {
          userStore.loginAfter();
        }
        return true;
      } else {
        $router.error('InitError', res.msg || '加载失败');
      }
    },
  },
  persist: {
    enabled: true,
    strategies: [
      {
        key: 'app-store',
      },
    ],
  },
});

// TODO: @owen 先做数据适配，后期重构
const adaptTemplate = async (appTemplate: AppStoreState['template'], templateId: string | null): Promise<void> => {
  const { data: diyTemplate } = templateId
    // 查询指定模板，一般是预览时使用
    ? await DiyApi.getDiyTemplate(templateId)
    : await DiyApi.getUsedDiyTemplate();
  // 模板不存在
  if (!diyTemplate) {
    $router.error('TemplateError');
    return;
  }

  const tabBar = diyTemplate?.property?.tabBar;
  if (tabBar) {
    appTemplate.basic.tabBar = tabBar;
    if (tabBar?.theme) {
      appTemplate.basic.theme = tabBar?.theme;
    }
  }
  appTemplate.home = diyTemplate?.home;
  appTemplate.user = diyTemplate?.user;
}

export default app;
